package com.csdj.t301.cloud.uitls;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * author:cloud
 * date:2021/1/21 0021
 **/
public class RelfectUtil {

    public static Object invoke(String className,String methodName,Object... params){
        boolean paramsNull = true;
        Class[] classes = null;
        if(params != null){
            paramsNull = false;
            classes = new Class[params.length];
            for (int i = 0; i < params.length; i++) {
                classes[i] = params[i].getClass();
            }
        }

        try {
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();
            Method method;
            if(paramsNull){
                method = clazz.getMethod(methodName);
            }else{
                method = clazz.getMethod(methodName,classes);
            }
            return method.invoke(obj,params);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将map 转化成实体实例
     * @param map
     * @param entity
     * @return
     */
    public static Object mapToEntity(Map<String,String> map, String entity){
        try {
            Class clazz = Class.forName(entity);
            Object obj = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for(Field field : fields){
                String fieldName = field.getName();
                String value = map.get(fieldName);
                if(value == null){
                    continue;
                }else{
                    field.setAccessible(true);
                    field.set(obj,value);
                }
            }
            return obj;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
